package mo.offer_version2;

public class L53_1 {

    public int search(int[] nums, int target) {
        if (nums.length == 0) {
            return 0;
        }
        int left = 0, right = nums.length - 1;
        int mid = -1;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                break;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        if (nums[mid] != target) {
            return 0;
        } else {
            int count = 1;
            left = mid - 1;
            while (left >= 0 && nums[left] == target) {
                left--;
                count++;
            }
            right = mid + 1;
            while (right < nums.length && nums[right] == target) {
                right++;
                count++;
            }
            return count;
        }
    }

}
